package com.atuguigu.flink.Day05;

import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

// 使用迟到元素更新窗口计算结果
public class Example2_2 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        env
                .socketTextStream("localhost",9999)
                .map(
                        new MapFunction<String, Tuple2<String,Long>>() {
                            @Override
                            public Tuple2<String, Long> map(String value) throws Exception {
                                String[] arr = value.split(" ");
                                return Tuple2.of(arr[0],Long.parseLong(arr[1]) * 1000L);
                            }
                        }
                )
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<Tuple2<String, Long>>forBoundedOutOfOrderness(Duration.ofSeconds(5))
                        .withTimestampAssigner(new SerializableTimestampAssigner<Tuple2<String,Long>>() {
                            @Override
                            public long extractTimestamp(Tuple2<String, Long> element, long recordTimestamp) {
                                return element.f1;
                            }
                        })
                )
                .keyBy(r->r.f0)
                .window(TumblingEventTimeWindows.of(Time.seconds(5)))
                .allowedLateness(Time.seconds(5))//等待5s的迟到事件
                .process(new ProcessWindowFunction<Tuple2<String, Long>, String, String, TimeWindow>() {
                    @Override
                    public void process(String s, Context context, Iterable<Tuple2<String, Long>> elements, Collector<String> out) throws Exception {
                        long count = elements.spliterator().getExactSizeIfKnown();
                        //用来定义窗口状态，如果水位线到达，则窗口关闭，触发
                ValueState<Boolean> isaction = context.windowState().getState(new ValueStateDescriptor<Boolean>("action", Types.BOOLEAN));
                        if(isaction.value() == null){
                            //证明是第一次，触发窗口，到达水位线,关闭窗口
                            out.collect("第一次触发窗口,总个数为" + count +"个元素");
                            isaction.update(true);
                        }else if(isaction !=null && isaction.value() == true){
                            out.collect("并不是第一次触发窗口,为迟到元素,现在的元素共有" +count +"个");
                        }


                    }
                })
                .print();

        env.execute();
    }
}
